package com.algorithm;

/**
 * @author: sun.hongliang
 * @create: 2019/07/19 14:41
 */
public class AtoiTest {

    public static void main(String[] args) {
        System.out.println(atoi("-2147483647"));
    }

    public static int atoi(String str) {
        char[] chars = str.toCharArray();
        int length = chars.length;
        int startIndex = length;
        for (int i = 0; i < length; i++) {
            char temp = chars[i];
            if (temp == ' ') {
                continue;
            }
            if (temp == '-') {
                startIndex = i;
                break;
            }
            if (temp == '+') {
                startIndex = i;
                break;
            }

            if (temp >= '0' && temp <= '9') {
                startIndex = i;
                break;
            }
            startIndex = i;
            break;
        }
        if (startIndex > length - 1) {
            return 0;
        }

        long result = 0;
        boolean isFirstFuChar = chars[startIndex] == '-' || chars[startIndex] == '+';
        boolean isFu = chars[startIndex] == '-';
        for (int j = isFirstFuChar ? startIndex + 1 : startIndex; j < length; j++) {
            char temp = chars[j];
            if (temp >= '0' && temp <= '9') {
                result = result * 10 + Integer.parseInt(String.valueOf(temp));
                if (isFu && result * -1 <= Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                } else if (!isFu && result >= Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                continue;
            } else {
                break;
            }
        }
        return isFu ? (int) result * -1 : (int) result;
    }
}
